package com.cqemme.comm.po;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * ClassName: DynamicSetterAndGetter
 *
 * @Author Tommy
 * @Description : TODO
 * @Date 16:30 2019/6/5
 *
 **/
public class DynamicSetterAndGetter {
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static <T> T get(Object obj, String filed) {

		Object result = null;
		try {

			Class clazz = obj.getClass();

			PropertyDescriptor pd = new PropertyDescriptor(filed, clazz);

			Method getMethod = pd.getReadMethod();

			result = getMethod.invoke(obj);

		} catch (SecurityException | InvocationTargetException | IllegalArgumentException | IntrospectionException | IllegalAccessException e) {
			e.printStackTrace();
		}

		return (T) result;

	}

	@SuppressWarnings("deprecation")
	public static void set(Object obj, String field, String value) {

		@SuppressWarnings("rawtypes")
        Class clazz = obj.getClass();
		PropertyDescriptor pd;
		try {
			pd = new PropertyDescriptor(field, clazz);
			Method setMethod = pd.getWriteMethod();
			Class<?> class1 = pd.getPropertyType();

			if (class1.isAssignableFrom(Integer.class)) {
				DynamicSetterAndGetter.add(setMethod, obj, Integer.parseInt(value));
			} else if (class1.isAssignableFrom(Double.class)) {
				DynamicSetterAndGetter.add(setMethod, obj, Double.parseDouble(value));
			} else if (class1.isAssignableFrom(Boolean.class)) {
				DynamicSetterAndGetter.add(setMethod, obj, Boolean.parseBoolean(value));
			} else if (class1.isAssignableFrom(String.class)) {
				DynamicSetterAndGetter.add(setMethod, obj, value);
			} else if (class1.isAssignableFrom(Float.class)) {
				DynamicSetterAndGetter.add(setMethod, obj, Float.parseFloat(value));
			} else if (class1.isAssignableFrom(Long.class)) {
				DynamicSetterAndGetter.add(setMethod, obj, Long.parseLong(value));
			} else if (class1.isAssignableFrom(Date.class)) {
				DynamicSetterAndGetter.add(setMethod, obj, Date.parse(value));
			}
		} catch (IntrospectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private static <T> void add(Method setMethod, Object obj, T value) {

		try {
			setMethod.invoke(obj, value);
		} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
